//
//  EditViewController.m
//  SAT_NET
//
//  Created by lanou3g on 16/3/4.
//  Copyright © 2016年 郭丹. All rights reserved.
//

#import "EditViewController.h"
#import "SortCell.h"


@interface EditViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionV;

@property(nonatomic, strong) NSMutableArray *arrayAllData;
@property(nonatomic, strong) UIButton *editButton;
@property(nonatomic, strong) UILabel *hidenLable;



@end

@implementation EditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setData];
    [self setViews];
    [self setDelegate];
    

    
    [self.collectionV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"id"];
    [self.collectionV registerClass:[SortCell class] forCellWithReuseIdentifier:@"collection_id"];
    
    [self.collectionV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head_id"];
    
    // 设置大小后可见
    ((UICollectionViewFlowLayout *)self.collectionV.collectionViewLayout).headerReferenceSize = CGSizeMake(kScreenW, 30);
    
    
    
//    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    UIPanGestureRecognizer *tap = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
//    [self.collectionV addGestureRecognizer:tap];
    
}

- (void)longPressAction:(UIPanGestureRecognizer *)sender {
    
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:{
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.collectionV indexPathForItemAtPoint:[sender locationInView:self.collectionV]];
            if (indexPath == nil) {
                break;
            }
            //在路径上则开始移动该路径上的cell
            [self.collectionV beginInteractiveMovementForItemAtIndexPath:indexPath];
            break;
        }
        case UIGestureRecognizerStateChanged:{
            //移动过程当中随时更新cell位置
            [self.collectionV updateInteractiveMovementTargetPosition:[sender locationInView:self.collectionV]];
            break;
        }
        case UIGestureRecognizerStateEnded:{
            //移动结束后关闭cell移动
            [self.collectionV endInteractiveMovement];
            break;
        }
            
        default:
            [self.collectionV cancelInteractiveMovement];
            break;
    }
    
    
}
// 是否允许移动
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
//    if (self.editButton.selected) {
//        return YES;
//    } else if (indexPath.row == 1) {
//        return YES;
//    }
//    return NO;
    
    return YES;
}
// 移动
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    if (sourceIndexPath.section == destinationIndexPath.section) {
//        self.arrayAddData = self.collectionV.
        return;
    }
    
    // 获取移除对象
    id item0 = [self.arrayAddData objectAtIndex:sourceIndexPath.item];
    
    // 数据操作
    [self.arrayAddData removeObject:item0];
    [self.arrayRemoveData insertObject:item0 atIndex:destinationIndexPath.item];
    
    
    NSLog(@"%@",self.arrayAddData);
    NSLog(@"%@",self.arrayRemoveData);
    
}

//- (void)sendMessage:(selectChannel)blcok {
//    self.block = blcok;
//}

- (void)returnSortArray:(sortArrayBlock)sortArrBlock {
    self.sortArrBlock = sortArrBlock;
}


#pragma mark 点击cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (!self.editButton.selected) {//未编辑状态
        
        if (indexPath.section == 0) {
            self.indexToShow = indexPath.row;
            NSLog(@"%ld",self.indexToShow);
            [self cancel:nil];
        } else {
            // 移动到第0组
//            NSIndexPath *ind = [collectionView index]
            NSIndexPath *indexP = [NSIndexPath indexPathForRow:self.arrayAddData.count - 1 inSection:0];
            [self.arrayAddData addObject:self.arrayRemoveData[indexP.row]];
            [self.arrayRemoveData removeObject:self.arrayRemoveData[indexPath.row]];
            [collectionView moveItemAtIndexPath:indexPath toIndexPath:indexP];
            [self.collectionV reloadData];
            
            NSLog(@"section0 = %ld,section1 = %ld",indexP.row,indexPath.row);
            
            
        }
        
        
    } else {// 编辑状态
        
    }
    
//    NSLog(@"%ld,%ld",indexPath.section,indexPath.row);
    
}


- (void)changeState:(UIButton *)sender {

    self.editButton.selected = !self.editButton.selected;
    if (self.editButton.selected) {
        [self.editButton setTitle:@"完成" forState:(UIControlStateNormal)];
//        // 点击后的返现效果关掉
//        self.editButton.adjustsImageWhenHighlighted = NO;
        [self.editButton setHighlighted:NO];
        self.hidenLable.hidden = NO;
        
    } else {
        [self.editButton setTitle:@"编辑" forState:(UIControlStateNormal)];
        self.hidenLable.hidden = YES;
    }
    
    
    
    NSLog(@"2  %d",sender.selected);
}
#pragma mark 返回按钮
- (IBAction)cancel:(id)sender {
    
    self.sortArrBlock(self.arrayAddData,self.indexToShow);
    NSLog(@"%@",self.arrayAddData);
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)setData {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"sort" ofType:@"plist"];
    self.arrayAllData = [NSMutableArray arrayWithContentsOfFile:filePath];
    
    for (NSString *str in self.arrayAllData) {
        if ([self.arrayAddData containsObject:str] == NO) {
            [self.arrayRemoveData addObject:str];
        }
    }
}

- (void)setViews {
    
    //添加NavigationController
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self];
    self.title = @"更多";
    nav.navigationBar.frame = CGRectMake(0, 20, kScreenW, 44);
    nav.navigationBar.backgroundColor = [UIColor redColor];
    nav.navigationBar.translucent = YES;
    [self.view addSubview:nav.view];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"cancel"] style:(UIBarButtonItemStyleDone) target:self action:@selector(rightAction)];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(60, 30);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 20;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectionV.backgroundColor = [UIColor colorWithRed:242 / 255.0
                                                       green:242 / 255.0
                                                        blue:242 / 255.0
                                                       alpha:1];
}

- (void)rightAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)setDelegate {
    self.collectionV.delegate = self;
    self.collectionV.dataSource = self;
    [self.view addSubview:self.collectionV];
}

- (NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return self.arrayAddData.count;
    } else {
        return self.arrayRemoveData.count;
    }
}

- (NSInteger )numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SortCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection_id" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.lable.text = self.arrayAddData[indexPath.row];
    } else {
        cell.lable.text = self.arrayRemoveData[indexPath.row];
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    cell.layer.cornerRadius = 15;
    cell.layer.masksToBounds = YES;
    return cell;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(60, 30);
}

- (UIEdgeInsets )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
// 头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head_id" forIndexPath:indexPath];
        if (indexPath.section == 0) {
            
            UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 80, 30)];
            lable.text = @"点击切换频道";
            lable.font = [UIFont systemFontOfSize:12];
            [view addSubview:lable];
            
            self.hidenLable = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 100, 30)];
            self.hidenLable.text = @"拖拽可调节顺序";
            self.hidenLable.font = [UIFont systemFontOfSize:12];
            // 设置提示首次进入隐藏
            self.hidenLable.hidden = YES;
            self.hidenLable.alpha = 0.4;
            [view addSubview:self.hidenLable];
            
            self.editButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
            [self.editButton addTarget:self action:@selector(changeState:) forControlEvents:(UIControlEventTouchUpInside)];
            [self.editButton setFrame:CGRectMake(310, 0, 60, 30)];
            [self.editButton setTitle:@"编辑" forState:(UIControlStateNormal)];
            [view addSubview:self.editButton];
            return view;
            
        } else {
            
            UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 80, 20)];
            lable.text = @"点击添加频道";
            lable.font = [UIFont systemFontOfSize:12];
            [view addSubview:lable];
            return view;
        }
    } else {
        return nil;
    }
    
    
}



- (NSMutableArray *)arrayRemoveData {
    if (!_arrayRemoveData) {
        _arrayRemoveData = [NSMutableArray array];
    }
    return _arrayRemoveData;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
